<template>
  <div class="mod-faceDraftList">
    <!-- 搜索表单 -->
    <el-form :inline="true" :model="dataForm" class="demo-form-inline">
      <el-form-item label="设计稿名称">
        <el-input
          v-model="dataForm.draftName"
          placeholder="设计稿名称"
          clearable
        />
      </el-form-item>
      <el-form-item label="草稿状态">
        <el-select
          v-model="dataForm.draftStatus"
          placeholder="草稿状态"
          clearable
        >
          <el-option
            v-for="item in draftStatusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="排单状态">
        <el-select
          v-model="dataForm.scheduleStatus"
          placeholder="排单状态"
          clearable
        >
          <el-option
            v-for="item in scheduleStatusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="onSearch({})">查询</el-button>
        <el-button @click="clearSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 数据表格 -->
    <avue-crud
      ref="crud"
      :page="page"
      :data="dataList"
      :table-loading="dataListLoading"
      :option="tableOption"
      @selection-change="selectionChange"
      @on-load="getDataList"
      @search-change="onSearch"
    >
      <template slot="menuLeft">
        <el-button
          type="danger"
          @click="deleteHandle()"
          :disabled="dataListSelections.length <= 0"
          size="small"
          >批量删除</el-button
        >
      </template>

      <template slot="draftStatus" slot-scope="scope">
        <el-tag :type="getDraftStatusTagType(scope.row.draftStatus)">
          {{ getDraftStatusLabel(scope.row.draftStatus) }}
        </el-tag>
      </template>

      <template slot="scheduleStatus" slot-scope="scope">
        <el-tag :type="getScheduleStatusTagType(scope.row.scheduleStatus)">
          {{ getScheduleStatusLabel(scope.row.scheduleStatus) }}
        </el-tag>
      </template>

      <template slot="thumbnailUrl" slot-scope="scope">
        <div class="image-container">
          <el-image
            v-if="scope.row.thumbnailUrl"
            :src="scope.row.thumbnailUrl"
            :preview-src-list="[scope.row.thumbnailUrl]"
            fit="cover"
            class="thumbnail-image"
            :z-index="9999"
          >
            <template #error>
              <div class="image-error">
                <i class="el-icon-picture-outline"></i>
                <span>加载失败</span>
              </div>
            </template>
          </el-image>
          <div v-else class="no-image">
            <i class="el-icon-picture-outline"></i>
            <span>无图片</span>
          </div>
        </div>
      </template>

      <template #menu="scope">
        <el-button type="text" size="small" @click="viewHandle(scope.row)"
          >查看</el-button
        >
        <el-button
          v-if="scope.row.scheduleStatus === 1"
          type="text"
          size="small"
          @click="confirmSchedule(scope.row)"
          >确认排单</el-button
        >
        <!-- <el-button
          type="text"
          size="small"
          @click="deleteHandle(scope.row.draftId)"
          >删除</el-button
        > -->
      </template>
    </avue-crud>

    <!-- 分页 -->
    <el-pagination
      :current-page="page.currentPage"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="page.pageSize"
      :total="page.total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
    />

    <!-- 确认排单对话框 -->
    <el-dialog
      v-model="scheduleDialogVisible"
      title="确认排单"
      width="30%"
      :close-on-click-modal="false"
    >
      <el-form
        :model="scheduleForm"
        :rules="scheduleRules"
        ref="scheduleFormRef"
        label-width="100px"
      >
        <el-form-item label="订单金额" prop="orderAmount">
          <el-input-number
            v-model="scheduleForm.orderAmount"
            :precision="2"
            :step="0.01"
            :min="0"
            style="width: 100%"
          ></el-input-number>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="scheduleDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitSchedule">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import http from "@/utils/http";
import { tableOption } from "@/crud/order/faceDraftList.js";

// 响应式数据
const dataList = ref([]);
const dataListLoading = ref(false);
const dataListSelections = ref([]);
const crud = ref(null);
const dataForm = reactive({
  draftName: "",
  draftStatus: "",
  scheduleStatus: "",
});
const page = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 10,
});

// 排单对话框相关
const scheduleDialogVisible = ref(false);
const scheduleFormRef = ref(null);
const scheduleForm = reactive({
  draftId: "",
  orderAmount: 0,
});
const scheduleRules = {
  orderAmount: [
    { required: true, message: "请输入订单金额", trigger: "blur" },
    { type: "number", min: 0, message: "订单金额必须大于0", trigger: "blur" },
  ],
};

// 草稿状态选项
const draftStatusOptions = [
  { value: 1, label: "草稿" },
  { value: 2, label: "设计稿" },
];

// 排单状态选项
const scheduleStatusOptions = [
  { value: 0, label: "未排单" },
  { value: 1, label: "待确认排单" },
  { value: 2, label: "已确认排单" },
  { value: 3, label: "已生成订单" },
];

// 获取草稿状态标签类型
const getDraftStatusTagType = (status) => {
  switch (status) {
    case 0:
      return "info";
    case 1:
      return "warning";
    case 2:
      return "success";
    case 3:
      return "danger";
    default:
      return "info";
  }
};

// 获取草稿状态标签文本
const getDraftStatusLabel = (status) => {
  const option = draftStatusOptions.find((item) => item.value === status);
  return option ? option.label : "未知";
};

// 获取排单状态标签类型
const getScheduleStatusTagType = (status) => {
  switch (status) {
    case 0:
      return "info";
    case 1:
      return "primary";
    case 2:
      return "warning";
    case 3:
      return "success";
    default:
      return "info";
  }
};

// 获取排单状态标签文本
const getScheduleStatusLabel = (status) => {
  const option = scheduleStatusOptions.find((item) => item.value === status);
  return option ? option.label : "未知";
};

/**
 * 条件查询
 */
const onSearch = (params, done) => {
  // 如果有设计稿名称，添加到参数中
  if (dataForm.draftName) {
    params.draftName = dataForm.draftName;
  }
  getDataList(page, params, done);
};

// 获取数据列表
const getDataList = (pageParam, params, done) => {
  dataListLoading.value = true;
  http({
    url: http.adornUrl("/admin/faceDraft/pageByScheduleStatus"),
    method: "get",
    params: http.adornParams(
      Object.assign(
        {
          current: pageParam == null ? page.currentPage : pageParam.currentPage,
          size: pageParam == null ? page.pageSize : pageParam.pageSize,
          draftStatus: dataForm.draftStatus || undefined,
          scheduleStatus: dataForm.scheduleStatus || undefined,
        },
        params
      )
    ),
  })
    .then(({ data }) => {
      dataList.value = data.records || data.list || [];
      page.total = data.total || 0;
      dataListLoading.value = false;
      if (done) done();
    })
    .catch(() => {
      dataListLoading.value = false;
      if (done) done();
    });
};

// 清空搜索
const clearSearch = () => {
  dataForm.draftName = "";
  dataForm.draftStatus = "";
  dataForm.scheduleStatus = "";
  page.currentPage = 1;
  getDataList(page);
};

// 每页数改变
const sizeChangeHandle = (val) => {
  page.pageSize = val;
  page.currentPage = 1;
  getDataList(page);
};

// 当前页改变
const currentChangeHandle = (val) => {
  page.currentPage = val;
  getDataList(page);
};

// 多选
const selectionChange = (selection) => {
  dataListSelections.value = selection;
};

// 查看详情
const viewHandle = (row) => {
  ElMessage.info(`查看设计稿详情: ${row.draftName}`);
  // 这里可以添加跳转到详情页的逻辑
};

// 更新排单状态
const updateScheduleStatus = (row) => {
  ElMessage.info(`更新排单状态: ${row.draftName}`);
  // 这里可以添加更新排单状态的逻辑
};

// 删除
const deleteHandle = (id) => {
  const ids = id ? [id] : dataListSelections.value.map((item) => item.draftId);
  if (ids.length === 0) {
    ElMessage.warning("请选择要删除的数据");
    return;
  }

  ElMessageBox.confirm(
    `确定对选中的${ids.length}条数据进行[${id ? "删除" : "批量删除"}]操作?`,
    "提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  ).then(() => {
    http({
      url: http.adornUrl("/admin/faceDraft/delete"),
      method: "post",
      data: http.adornData(ids, false),
    }).then(({ data }) => {
      if (data && data.code === 0) {
        ElMessage.success("操作成功");
        getDataList(page);
      } else {
        ElMessage.error(data.msg || "操作失败");
      }
    });
  });
};

// 提交草稿
const submitDraft = (draftId) => {
  ElMessageBox.confirm("确定提交该草稿吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    http({
      url: http.adornUrl("/admin/faceDraft/submit"),
      method: "post",
      data: http.adornData({ draftId }),
    }).then(({ data }) => {
      if (data && data.code === 0) {
        ElMessage.success("提交成功");
        getDataList(page);
      } else {
        ElMessage.error(data.msg || "提交失败");
      }
    });
  });
};

// 确认排单
const confirmSchedule = (row) => {
  scheduleForm.draftId = row.draftId;
  scheduleForm.orderAmount = 0;
  scheduleDialogVisible.value = true;
};

// 提交排单
const submitSchedule = () => {
  scheduleFormRef.value.validate((valid) => {
    if (valid) {
      http({
        url: http.adornUrl("/admin/faceDraft/confirmSchedule"),
        method: "post",
        headers: {
          "Content-Type": "application/x-www-form-urlencoded",
        },
        data: `draftId=${
          scheduleForm.draftId
        }&orderAmount=${scheduleForm.orderAmount.toFixed(2)}`,
      })
        .then(({ data }) => {
            ElMessage.success("排单成功");
            scheduleDialogVisible.value = false;
            getDataList(page);
        })
        .catch(() => {
          ElMessage.error("排单失败");
        });
    }
  });
};

// 初始化
onMounted(() => {
  getDataList(page);
});
</script>

<style lang="scss" scoped>
.mod-faceDraftList {
  .el-form {
    background-color: #fff;
    padding: 20px;
    margin-bottom: 20px;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }

  .el-table {
    margin-bottom: 20px;
  }

  .el-pagination {
    margin-top: 20px;
    text-align: right;
  }

  .image-container {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 60px;
    height: 60px;
  }

  .thumbnail-image {
    max-width: 100%;
    max-height: 100%;
    object-fit: cover;
    border-radius: 4px;
  }

  .no-image {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: #909399;
    font-size: 12px;
    width: 100%;
    height: 100%;

    i {
      font-size: 20px;
      margin-bottom: 4px;
    }
  }

  .image-error {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: #909399;
    font-size: 12px;
    width: 100%;
    height: 100%;

    i {
      font-size: 20px;
      margin-bottom: 4px;
    }
  }
}
</style>
